package com.springboot.jwt.interceptor;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.springboot.jwt.utils.JwtUtil;
import com.tutorials.common.utils.R;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

public class JwtInterceptors implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 从请求头中获取令牌
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        String message = "";
        try {
            JwtUtil.verify(token);
            return true;
        } catch (SignatureVerificationException e) {
            message = "无效签名";
        } catch (TokenExpiredException e) {
            message = "token已过期";
        } catch (AlgorithmMismatchException e) {
            message = "算法不一致";
        } catch (Exception e) {
            message = "token无效";
        }
        String json = new ObjectMapper().writeValueAsString(R.error(400000, message));
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().println(json);

        return false;
    }
}
